#include "t_rules.h"
#include <QGlobalStatic>
#include <QIcon>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QButtonGroup>
#include <cmath>
#include <QDebug>
#include "ElaText.h"
#include "ElaLineEdit.h"
#include "ElaRadioButton.h"
#include "ElaCheckBox.h"
#include "ElaPushButton.h"
#include "ElaComboBox.h"
#include "ElaScrollPageArea.h"
#include "ElaMessageBar.h"
#include "t_excel.h"

Q_GLOBAL_STATIC(T_Rules,s_instance)
double g_duan_value_H = 0.0;
double g_duan_value_V = 0.0;

T_Rules::T_Rules(QWidget *parent)
    : T_BasePage(parent)
{
    initBlockInfo();
    initParams();
    initModelGroup();
    initUI();
}

T_Rules::~T_Rules()
{

}

T_Rules *T_Rules::Instance()
{
    return s_instance;
}

void T_Rules::initUI()
{
    ElaText *blockInfoText = new ElaText("电芯参数", this);
    blockInfoText->setWordWrap(false);
    blockInfoText->setTextPixelSize(15);

    ElaText *paramsText = new ElaText("PACK参数", this);
    paramsText->setWordWrap(false);
    paramsText->setTextPixelSize(15);

    ElaText *modelGroupText = new ElaText("模组参数", this);
    modelGroupText->setWordWrap(false);
    modelGroupText->setTextPixelSize(15);

    ElaPushButton *okBtn = new ElaPushButton("开始生成",this);
    connect(okBtn,&ElaPushButton::clicked,this,[=](){
        if(m_is_allow_create) {
            createItem();
        } else {
            ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","已改变参数配置，请点击计算数量按钮重新计算模组数量",3000,this->parentWidget());
        }
    });
    QHBoxLayout *btnLayout = new QHBoxLayout();
    btnLayout->addStretch();
    btnLayout->addWidget(okBtn);
    btnLayout->addStretch();

    QWidget* centralWidget = new QWidget(this);
    centralWidget->setWindowTitle("规则配置");
    QVBoxLayout* centerLayout = new QVBoxLayout(centralWidget);
    centerLayout->addWidget(blockInfoText);
    centerLayout->addSpacing(2);
    centerLayout->addWidget(m_blockInfoArea);
    centerLayout->addSpacing(5);
    centerLayout->addWidget(paramsText);
    centerLayout->addSpacing(2);
    centerLayout->addWidget(m_paramsArea);
    centerLayout->addSpacing(5);
    centerLayout->addWidget(modelGroupText);
    centerLayout->addSpacing(2);
    centerLayout->addWidget(m_modelGroupArea);
    centerLayout->addSpacing(2);
    centerLayout->addLayout(btnLayout);
    centerLayout->addStretch();
    centerLayout->setContentsMargins(0, 0, 0, 0);
    addCentralWidget(centralWidget, true, true, 0);
}

void T_Rules::initBlockInfo()
{
    ElaText *blockInfo_jgtype_text = new ElaText("结构类型：",this);
    blockInfo_jgtype_text->setWordWrap(false);
    blockInfo_jgtype_text->setTextPixelSize(12);
    ElaText *blockInfo_jgtype_text_2 = new ElaText("",this);
    blockInfo_jgtype_text_2->setWordWrap(false);
    blockInfo_jgtype_text_2->setTextPixelSize(13);
    ElaText *blockInfo_txtype_text = new ElaText("体系类型：",this);
    blockInfo_txtype_text->setWordWrap(false);
    blockInfo_txtype_text->setTextPixelSize(12);
    ElaText *blockInfo_txtype_text_2 = new ElaText("",this);
    blockInfo_txtype_text_2->setWordWrap(false);
    blockInfo_txtype_text_2->setTextPixelSize(13);
    ElaText *blockInfo_inTemp_text = new ElaText("充电温度：",this);
    blockInfo_inTemp_text->setWordWrap(false);
    blockInfo_inTemp_text->setTextPixelSize(12);
    ElaText *blockInfo_inTemp_text_2 = new ElaText("",this);
    blockInfo_inTemp_text_2->setWordWrap(false);
    blockInfo_inTemp_text_2->setTextPixelSize(13);
    ElaText *blockInfo_outTemp_text = new ElaText("放电温度：",this);
    blockInfo_outTemp_text->setWordWrap(false);
    blockInfo_outTemp_text->setTextPixelSize(12);
    ElaText *blockInfo_outTemp_text_2 = new ElaText("",this);
    blockInfo_outTemp_text_2->setWordWrap(false);
    blockInfo_outTemp_text_2->setTextPixelSize(13);

    QHBoxLayout* hLayout_1 = new QHBoxLayout();
    hLayout_1->addWidget(blockInfo_jgtype_text);
    hLayout_1->addSpacing(5);
    hLayout_1->addWidget(blockInfo_jgtype_text_2);
    hLayout_1->addSpacing(10);
    hLayout_1->addWidget(blockInfo_txtype_text);
    hLayout_1->addSpacing(5);
    hLayout_1->addWidget(blockInfo_txtype_text_2);
    hLayout_1->addSpacing(10);
    hLayout_1->addWidget(blockInfo_inTemp_text);
    hLayout_1->addSpacing(5);
    hLayout_1->addWidget(blockInfo_inTemp_text_2);
    hLayout_1->addSpacing(10);
    hLayout_1->addWidget(blockInfo_outTemp_text);
    hLayout_1->addSpacing(5);
    hLayout_1->addWidget(blockInfo_outTemp_text_2);
    hLayout_1->addSpacing(10);

    ElaText *blockInfo_kWh_text = new ElaText("额定容量Ah：",this);
    blockInfo_kWh_text->setWordWrap(false);
    blockInfo_kWh_text->setTextPixelSize(12);
    ElaText *blockInfo_kWh_text_2 = new ElaText("",this);
    blockInfo_kWh_text_2->setWordWrap(false);
    blockInfo_kWh_text_2->setTextPixelSize(13);
    ElaText *blockInfo_voltage_text = new ElaText("额定电压V：",this);
    blockInfo_voltage_text->setWordWrap(false);
    blockInfo_voltage_text->setTextPixelSize(12);
    ElaText *blockInfo_voltage_text_2 = new ElaText("",this);
    blockInfo_voltage_text_2->setWordWrap(false);
    blockInfo_voltage_text_2->setTextPixelSize(13);
    ElaText *blockInfo_outStopVol_text = new ElaText("放电截至电压V：",this);
    blockInfo_outStopVol_text->setWordWrap(false);
    blockInfo_outStopVol_text->setTextPixelSize(12);
    ElaText *blockInfo_outStopVol_text_2 = new ElaText("",this);
    blockInfo_outStopVol_text_2->setWordWrap(false);
    blockInfo_outStopVol_text_2->setTextPixelSize(13);
    ElaText *blockInfo_inStopVol_text = new ElaText("充电截至电压V：",this);
    blockInfo_inStopVol_text->setWordWrap(false);
    blockInfo_inStopVol_text->setTextPixelSize(12);
    ElaText *blockInfo_inStopVol_text_2 = new ElaText("",this);
    blockInfo_inStopVol_text_2->setWordWrap(false);
    blockInfo_inStopVol_text_2->setTextPixelSize(13);

    QHBoxLayout* hLayout_2 = new QHBoxLayout();
    hLayout_2->addWidget(blockInfo_kWh_text);
    hLayout_2->addSpacing(5);
    hLayout_2->addWidget(blockInfo_kWh_text_2);
    hLayout_2->addSpacing(10);
    hLayout_2->addWidget(blockInfo_voltage_text);
    hLayout_2->addSpacing(5);
    hLayout_2->addWidget(blockInfo_voltage_text_2);
    hLayout_2->addSpacing(10);
    hLayout_2->addWidget(blockInfo_outStopVol_text);
    hLayout_2->addSpacing(5);
    hLayout_2->addWidget(blockInfo_outStopVol_text_2);
    hLayout_2->addSpacing(10);
    hLayout_2->addWidget(blockInfo_inStopVol_text);
    hLayout_2->addSpacing(5);
    hLayout_2->addWidget(blockInfo_inStopVol_text_2);
    hLayout_2->addSpacing(10);

    ElaText *blockInfo_outContinue_text = new ElaText("持续放电倍率：",this);
    blockInfo_outContinue_text->setWordWrap(false);
    blockInfo_outContinue_text->setTextPixelSize(12);
    ElaText *blockInfo_outContinue_text_2 = new ElaText("",this);
    blockInfo_outContinue_text_2->setWordWrap(false);
    blockInfo_outContinue_text_2->setTextPixelSize(13);
    ElaText *blockInfo_inContinue_text = new ElaText("持续充电倍率：",this);
    blockInfo_inContinue_text->setWordWrap(false);
    blockInfo_inContinue_text->setTextPixelSize(12);
    ElaText *blockInfo_inContinue_text_2 = new ElaText("",this);
    blockInfo_inContinue_text_2->setWordWrap(false);
    blockInfo_inContinue_text_2->setTextPixelSize(13);
    ElaText *blockInfo_out10_text = new ElaText("10秒峰值放电倍率：",this);
    blockInfo_out10_text->setWordWrap(false);
    blockInfo_out10_text->setTextPixelSize(12);
    ElaText *blockInfo_out10_text_2 = new ElaText("",this);
    blockInfo_out10_text_2->setWordWrap(false);
    blockInfo_out10_text_2->setTextPixelSize(13);
    ElaText *blockInfo_recircle_text = new ElaText("循环：",this);
    blockInfo_recircle_text->setWordWrap(false);
    blockInfo_recircle_text->setTextPixelSize(12);
    ElaText *blockInfo_recircle_text_2 = new ElaText("",this);
    blockInfo_recircle_text_2->setWordWrap(false);
    blockInfo_recircle_text_2->setTextPixelSize(13);

    QHBoxLayout* hLayout_3 = new QHBoxLayout();
    hLayout_3->addWidget(blockInfo_outContinue_text);
    hLayout_3->addSpacing(5);
    hLayout_3->addWidget(blockInfo_outContinue_text_2);
    hLayout_3->addSpacing(10);
    hLayout_3->addWidget(blockInfo_inContinue_text);
    hLayout_3->addSpacing(5);
    hLayout_3->addWidget(blockInfo_inContinue_text_2);
    hLayout_3->addSpacing(10);
    hLayout_3->addWidget(blockInfo_out10_text);
    hLayout_3->addSpacing(5);
    hLayout_3->addWidget(blockInfo_out10_text_2);
    hLayout_3->addSpacing(10);
    hLayout_3->addWidget(blockInfo_recircle_text);
    hLayout_3->addSpacing(5);
    hLayout_3->addWidget(blockInfo_recircle_text_2);
    hLayout_3->addSpacing(10);

    ElaText *blockInfo_length_text = new ElaText("长度mm：",this);
    blockInfo_length_text->setWordWrap(false);
    blockInfo_length_text->setTextPixelSize(12);
    ElaText *blockInfo_length_text_2 = new ElaText("",this);
    blockInfo_length_text_2->setWordWrap(false);
    blockInfo_length_text_2->setTextPixelSize(13);
    ElaText *blockInfo_width_text = new ElaText("宽度mm：",this);
    blockInfo_width_text->setWordWrap(false);
    blockInfo_width_text->setTextPixelSize(12);
    ElaText *blockInfo_width_text_2 = new ElaText("",this);
    blockInfo_width_text_2->setWordWrap(false);
    blockInfo_width_text_2->setTextPixelSize(13);
    ElaText *blockInfo_height_text = new ElaText("高度mm：",this);
    blockInfo_height_text->setWordWrap(false);
    blockInfo_height_text->setTextPixelSize(12);
    ElaText *blockInfo_height_text_2 = new ElaText("",this);
    blockInfo_height_text_2->setWordWrap(false);
    blockInfo_height_text_2->setTextPixelSize(13);
    ElaText *blockInfo_weight_text = new ElaText("重量g：",this);
    blockInfo_weight_text->setWordWrap(false);
    blockInfo_weight_text->setTextPixelSize(12);
    ElaText *blockInfo_weight_text_2 = new ElaText("",this);
    blockInfo_weight_text_2->setWordWrap(false);
    blockInfo_weight_text_2->setTextPixelSize(13);

    QHBoxLayout* hLayout_4 = new QHBoxLayout();
    hLayout_4->addWidget(blockInfo_length_text);
    hLayout_4->addSpacing(5);
    hLayout_4->addWidget(blockInfo_length_text_2);
    hLayout_4->addSpacing(10);
    hLayout_4->addWidget(blockInfo_width_text);
    hLayout_4->addSpacing(5);
    hLayout_4->addWidget(blockInfo_width_text_2);
    hLayout_4->addSpacing(10);
    hLayout_4->addWidget(blockInfo_height_text);
    hLayout_4->addSpacing(5);
    hLayout_4->addWidget(blockInfo_height_text_2);
    hLayout_4->addSpacing(10);
    hLayout_4->addWidget(blockInfo_weight_text);
    hLayout_4->addSpacing(5);
    hLayout_4->addWidget(blockInfo_weight_text_2);
    hLayout_4->addSpacing(10);


    ElaComboBox *blockCombobox = new ElaComboBox(this);
    blockCombobox->setMinimumWidth(200);
    connect(blockCombobox,&ElaComboBox::currentTextChanged,[=](const QString &text){
        m_blockInfo = g_block_map[text];
        blockInfo_jgtype_text_2->setText(m_blockInfo.jgtype);
        blockInfo_txtype_text_2->setText(m_blockInfo.txtype);
        blockInfo_kWh_text_2->setText(QString::number(m_blockInfo.kWh,'f',2));
        blockInfo_voltage_text_2->setText(QString::number(m_blockInfo.voltage,'f',2));
        blockInfo_outStopVol_text_2->setText(QString::number(m_blockInfo.outStopVol,'f',2));
        blockInfo_inStopVol_text_2->setText(QString::number(m_blockInfo.inStopVol,'f',2));
        blockInfo_outContinue_text_2->setText(m_blockInfo.outContinue);
        blockInfo_out10_text_2->setText(m_blockInfo.out10);
        blockInfo_inContinue_text_2->setText(m_blockInfo.inContinue);
        blockInfo_inTemp_text_2->setText(m_blockInfo.inTemp);
        blockInfo_outTemp_text_2->setText(m_blockInfo.outTemp);
        blockInfo_weight_text_2->setText(QString::number(m_blockInfo.weight));
        blockInfo_recircle_text_2->setText(QString::number(m_blockInfo.recircle));
        blockInfo_length_text_2->setText(QString::number(m_blockInfo.length,'f',2));
        blockInfo_width_text_2->setText(QString::number(m_blockInfo.width,'f',2));
        blockInfo_height_text_2->setText(QString::number(m_blockInfo.height,'f',2));

        if(m_blockInfo.jgtype.compare("软包") == 0) {
            m_duan_value_H = 50;
            m_duan_value_V = 50;
            g_duan_value_H = m_duan_value_H;
            //软件启动默认是水平，所以V为0
            g_duan_value_V = 0.0;
            m_pack_count_max = SOFTPACKCOUNTMAX;
            m_lwButton->show();
            m_lhButton->show();
            m_hwButton->hide();
            m_hlButton->show();
            m_whButton->hide();
            m_wlButton->show();
            m_lwButton->setChecked(true);
        } else {
            m_duan_value_H = 25;
            m_duan_value_V = 25;
            g_duan_value_H = m_duan_value_H;
            g_duan_value_V = 0.0;
            m_pack_count_max = SQUREPACKCOUNTMAX;
            m_lwButton->hide();
            m_lhButton->show();
            m_hwButton->hide();
            m_hlButton->show();
            m_whButton->hide();
            m_wlButton->hide();
            m_lhButton->setChecked(true);
        }

        if(!m_blockValueLe->text().isEmpty()){
            emit m_blockValueLe->editingFinished();
        }
        if(!m_blockAhValueLe->text().isEmpty()){
            emit m_blockAhValueLe->editingFinished();
        }

        m_is_allow_create = false;
    });
    ElaPushButton *importExcelBtn = new ElaPushButton("导入参数表",this);
    connect(importExcelBtn,&ElaPushButton::clicked,this,[=](){
        T_ExcelIns->ReadExcel();
        for(const auto &key : g_block_map.keys()) {
            blockCombobox->addItem(key);
        }
        if(blockCombobox->count() > 0) {
            m_is_import_excel = true;
        } else {
            ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","导入参数表失败",3000,this->parentWidget());
            m_is_import_excel = false;
        }
    });
    ElaText* blockText = new ElaText("产品型号", this);
    blockText->setWordWrap(false);
    blockText->setTextPixelSize(15);
    QHBoxLayout* blockLayout = new QHBoxLayout();
    blockLayout->addWidget(blockText);
    blockLayout->addStretch();
    blockLayout->addWidget(blockCombobox);
    blockLayout->addSpacing(10);
    blockLayout->addWidget(importExcelBtn);


    m_blockInfoArea = new ElaScrollPageArea(this);
    m_blockInfoArea->setFixedSize(700,200);
    QVBoxLayout* vLayout = new QVBoxLayout(m_blockInfoArea);
    vLayout->addLayout(blockLayout);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_1);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_2);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_3);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_4);
    vLayout->addStretch();
}

void T_Rules::initParams()
{
    ElaText *totalWText = new ElaText("整体长度",12,this);
    totalWText->setWordWrap(false);
    m_totalWLe = new ElaLineEdit(this);
    m_totalWLe->setText("800");
    m_totalWLe->setFixedHeight(20);
    connect(m_totalWLe,&ElaLineEdit::textEdited,this,[=](){
        m_is_allow_create = false;
    });
    ElaText *totalHText = new ElaText("整体宽度",12,this);
    totalHText->setWordWrap(false);
    m_totalHLe = new ElaLineEdit(this);
    m_totalHLe->setText("600");
    m_totalHLe->setFixedHeight(20);
    connect(m_totalHLe,&ElaLineEdit::textEdited,this,[=](){
        m_is_allow_create = false;
    });
    ElaText *totalHDText = new ElaText("整体厚度",12,this);
    totalHDText->setWordWrap(false);
    m_totalHDLe = new ElaLineEdit(this);
    m_totalHDLe->setText("300");
    m_totalHDLe->setFixedHeight(20);
    connect(m_totalHDLe,&ElaLineEdit::textEdited,this,[=](){
        m_is_allow_create = false;
    });
    QHBoxLayout *hLayout_1 = new QHBoxLayout();
    hLayout_1->addWidget(totalWText);
    hLayout_1->addWidget(m_totalWLe);
    hLayout_1->addStretch();
    hLayout_1->addWidget(totalHText);
    hLayout_1->addWidget(m_totalHLe);
    hLayout_1->addStretch();
    hLayout_1->addWidget(totalHDText);
    hLayout_1->addWidget(m_totalHDLe);

    ElaText *swapText = new ElaText("交换主体长宽",12,this);
    swapText->setWordWrap(false);
    ElaCheckBox *checkBox = new ElaCheckBox("是否交换",this);
    connect(checkBox,&ElaCheckBox::clicked,this,[=](bool checked){
        m_main_is_swap = checked;
        m_is_allow_create = false;
    });
    QHBoxLayout *hLayout_6 = new QHBoxLayout();
    hLayout_6->addWidget(swapText);
    hLayout_6->addStretch();
    hLayout_6->addWidget(checkBox);

    ElaText *blockValueText = new ElaText("额定电压V",12,this);
    blockValueText->setWordWrap(false);
    m_blockValueLe = new ElaLineEdit(this);
    m_blockValueLe->setFixedHeight(20);
    connect(m_blockValueLe,&ElaLineEdit::editingFinished,this,[=](){
        if(!m_is_import_excel){
            ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","请先导入电芯参数表",3000,this->parentWidget());
            return;
        }

        double sum = m_blockValueLe->text().toDouble();
        int num;
        double quotient = sum / m_blockInfo.voltage;
        // 使用浮点数比较代替取模运算
        if (std::abs(quotient - std::floor(quotient)) > std::numeric_limits<double>::epsilon()) {
            num = static_cast<int>(std::ceil(quotient));
        } else {
            num = static_cast<int>(quotient);
        }
        if(num % 2 != 0) {
            num += 1;
        }
        m_cLe->setText(QString::number(num));
        m_blockNumLe->setText(QString::number(num * m_bLe->text().toInt()));
        m_is_allow_create = false;
    });
    ElaText *blockAhValueText = new ElaText("额定容量Ah",12,this);
    blockValueText->setWordWrap(false);
    m_blockAhValueLe = new ElaLineEdit(this);
    m_blockAhValueLe->setFixedHeight(20);
    connect(m_blockAhValueLe,&ElaLineEdit::editingFinished,this,[=](){
        if(!m_is_import_excel){
            ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","请先导入电芯参数表",3000,this->parentWidget());
            return;
        }

        double sum = m_blockAhValueLe->text().toDouble();
        int num;
        double quotient = sum / m_blockInfo.kWh;
        // 使用浮点数比较代替取模运算
        if (std::abs(quotient - std::floor(quotient)) > std::numeric_limits<double>::epsilon()) {
            num = static_cast<int>(std::ceil(quotient));
        } else {
            num = static_cast<int>(quotient);
        }
        m_bLe->setText(QString::number(num));
        int sum1 = num * m_cLe->text().toInt();
        m_blockNumLe->setText(QString::number(sum1));
        m_is_allow_create = false;
    });
    QHBoxLayout *hLayout_2 = new QHBoxLayout();
    hLayout_2->addWidget(blockValueText);
    hLayout_2->addWidget(m_blockValueLe);
    hLayout_2->addStretch();
    hLayout_2->addWidget(blockAhValueText);
    hLayout_2->addWidget(m_blockAhValueLe);

    ElaText *cText = new ElaText("电芯串数",12,this);
    cText->setWordWrap(false);
    m_cLe = new ElaLineEdit(this);
    m_cLe->setFixedHeight(20);
    m_cLe->setReadOnly(true);
    ElaText *bHText = new ElaText("电芯并数",12,this);
    bHText->setWordWrap(false);
    m_bLe = new ElaLineEdit(this);
    m_bLe->setFixedHeight(20);
    m_bLe->setReadOnly(true);
    QHBoxLayout *hLayout_5 = new QHBoxLayout();
    hLayout_5->addWidget(cText);
    hLayout_5->addWidget(m_cLe);
    hLayout_5->addStretch();
    hLayout_5->addWidget(bHText);
    hLayout_5->addWidget(m_bLe);

    ElaText *blockNumText = new ElaText("总电芯数量",12,this);
    blockNumText->setWordWrap(false);
    m_blockNumLe = new ElaLineEdit(this);
    m_blockNumLe->setReadOnly(true);
    m_blockNumLe->setFixedHeight(20);

    ElaText *blockSingleNumText = new ElaText("单模组电芯数量",12,this);
    blockSingleNumText->setWordWrap(false);
    m_blockSingleNumLe = new ElaLineEdit(this);
    m_blockSingleNumLe->setReadOnly(true);
    m_blockSingleNumLe->setFixedHeight(20);

    QHBoxLayout *hLayout_3 = new QHBoxLayout();
    hLayout_3->addWidget(blockNumText);
    hLayout_3->addWidget(m_blockNumLe);
    hLayout_3->addStretch();
    hLayout_3->addWidget(blockSingleNumText);
    hLayout_3->addWidget(m_blockSingleNumLe);

    ElaText *hvText = new ElaText("放置方式",12,this);
    hvText->setWordWrap(false);
    m_hButton = new ElaRadioButton("水平",this);
    m_vButton = new ElaRadioButton("垂直",this);
    m_ddButton = new ElaRadioButton("堆叠",this);
    QButtonGroup* vhButtonGroup = new QButtonGroup(this);
    vhButtonGroup->addButton(m_hButton,0);
    vhButtonGroup->addButton(m_vButton,1);
    vhButtonGroup->addButton(m_ddButton,2);
    connect(vhButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, [=](QAbstractButton* button, bool isToggled) {
        if (isToggled)
        {            
            m_is_allow_create = false;
            int id = vhButtonGroup->id(button);
            if(id == 0){
                m_direction = 0;
                g_duan_value_H = m_duan_value_H;
                g_duan_value_V = 0;
            } else if(id == 1) {
                m_direction = 1;
                g_duan_value_H = 0;
                g_duan_value_V = m_duan_value_V;
            } else if(id == 2) {
                m_direction = 2;
                g_duan_value_H = 0;
                g_duan_value_V = 0;
            }
        }
    });
    m_hButton->setChecked(true);

    QHBoxLayout *hLayout_4 = new QHBoxLayout();
    hLayout_4->addWidget(hvText);
    hLayout_4->addStretch();
    hLayout_4->addWidget(m_hButton);
    hLayout_4->addWidget(m_vButton);
    hLayout_4->addWidget(m_ddButton);

    ElaText *lwhText = new ElaText("排列方式",12,this);
    lwhText->setWordWrap(false);
    m_lwButton = new ElaRadioButton("长宽",this);
    m_lhButton = new ElaRadioButton("长高",this);
    m_hwButton = new ElaRadioButton("高宽",this);
    m_wlButton = new ElaRadioButton("宽长",this);
    m_whButton = new ElaRadioButton("宽高",this);
    m_hlButton = new ElaRadioButton("高长",this);
    QButtonGroup* lwhlButtonGroup = new QButtonGroup(this);
    lwhlButtonGroup->addButton(m_lwButton,0);
    lwhlButtonGroup->addButton(m_lhButton,1);
    lwhlButtonGroup->addButton(m_hwButton,2);
    lwhlButtonGroup->addButton(m_wlButton,3);
    lwhlButtonGroup->addButton(m_whButton,4);
    lwhlButtonGroup->addButton(m_hlButton,5);
    connect(lwhlButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, [=](QAbstractButton* button, bool isToggled) {
        if (isToggled)
        {
            m_is_allow_create = false;
            int id = lwhlButtonGroup->id(button);
            if(id == 0){
                m_layout = LW;
                m_hButton->hide();
                m_vButton->hide();
                m_ddButton->show();
                m_ddButton->setChecked(true);
            } else if(id == 1) {
                m_layout = LH;
                m_hButton->hide();
                m_vButton->show();
                m_ddButton->hide();
                m_vButton->setChecked(true);
            } else if(id == 2) {
                m_layout = HW;
                m_hButton->hide();
                m_vButton->hide();
                m_ddButton->hide();
            } else if(id == 3) {
                m_layout = WL;
                m_hButton->hide();
                m_vButton->hide();
                m_ddButton->show();
                m_ddButton->setChecked(true);
            } else if(id == 4) {
                m_layout = WH;
                m_hButton->hide();
                m_vButton->hide();
                m_ddButton->hide();
            } else if(id == 5) {
                m_layout = HL;
                m_hButton->show();
                m_vButton->hide();
                m_ddButton->hide();
                m_hButton->setChecked(true);
            }
        }
    });
    m_lwButton->setChecked(true);
    QHBoxLayout *hLayout_7 = new QHBoxLayout();
    hLayout_7->addWidget(lwhText);
    hLayout_7->addStretch();
    hLayout_7->addWidget(m_lwButton);
    hLayout_7->addWidget(m_lhButton);
    hLayout_7->addWidget(m_hwButton);
    hLayout_7->addWidget(m_wlButton);
    hLayout_7->addWidget(m_whButton);
    hLayout_7->addWidget(m_hlButton);

    m_paramsArea = new ElaScrollPageArea(this);
    m_paramsArea->setFixedSize(700,240);
    QVBoxLayout* vLayout = new QVBoxLayout(m_paramsArea);
    vLayout->addLayout(hLayout_1);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_6);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_2);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_5);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_3);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_7);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_4);
    vLayout->addStretch();
}

void T_Rules::initModelGroup()
{
    ElaText *groupNumWText = new ElaText("模组个数",12,this);
    groupNumWText->setWordWrap(false);
    m_groupNumLe = new ElaLineEdit(this);
    m_groupNumLe->setFixedHeight(20);
    m_groupNumLe->setText("1");
    m_groupNumLe->setReadOnly(true);
    ElaPushButton *calcNumBtn = new ElaPushButton("计算数量",this);
    connect(calcNumBtn,&ElaPushButton::clicked,this,[=](){
        if(m_cLe->text().isEmpty() || m_bLe->text().isEmpty()) {
            ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","请先输入总电压和总容量得到串数和并数",3000,this->parentWidget());
            return;
        }
        if(m_totalWLe->text().isEmpty() || m_totalHLe->text().isEmpty() || m_totalHDLe->text().isEmpty()) {
            ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","请先输入结构的长、宽、厚度",3000,this->parentWidget());
            return;
        }

        m_is_allow_create = true;
        m_splitInt = 1;
        calcModelGroupCount();
    });
    QHBoxLayout *hLayout_1 = new QHBoxLayout();
    hLayout_1->addWidget(groupNumWText);
    hLayout_1->addStretch();
    hLayout_1->addWidget(m_groupNumLe);
    hLayout_1->addSpacing(10);
    hLayout_1->addWidget(calcNumBtn);

    ElaText *hzjText = new ElaText("排列方式",12,this);
    hzjText->setWordWrap(false);
    ElaRadioButton *hxButton = new ElaRadioButton("横向",this);
    ElaRadioButton *zxButton = new ElaRadioButton("纵向",this);
    ElaRadioButton *dhdlButton = new ElaRadioButton("多行多列",this);
    QButtonGroup* hzjButtonGroup = new QButtonGroup(this);
    hzjButtonGroup->addButton(hxButton,0);
    hzjButtonGroup->addButton(zxButton,1);
    hzjButtonGroup->addButton(dhdlButton,2);
    connect(hzjButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, [=](QAbstractButton* button, bool isToggled) {
        if (isToggled)
        {
            int id = hzjButtonGroup->id(button);
            if(id == 0){
                m_layout_group = HX;
            } else if(id == 1) {
                m_layout_group = ZX;
            } else if(id == 2) {
                m_layout_group = DHDL;
            }
        }
    });
    hxButton->setChecked(true);
    QHBoxLayout *hLayout_2 = new QHBoxLayout();
    hLayout_2->addWidget(hzjText);
    hLayout_2->addStretch();
    hLayout_2->addWidget(hxButton);
    hLayout_2->addWidget(zxButton);
    hLayout_2->addWidget(dhdlButton);

    m_modelGroupArea = new ElaScrollPageArea(this);
    QVBoxLayout* vLayout = new QVBoxLayout(m_modelGroupArea);
    vLayout->addLayout(hLayout_1);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_2);
    vLayout->addStretch();
}

void T_Rules::createItem()
{
    //根据预设创建
    //首先清空画布
    qInfo() << "清空画布";
    emit clearScene();
    double mainWidth;
    double mainHeight;
    if(m_main_is_swap) {
        mainWidth = m_totalHLe->text().toDouble();
        mainHeight = m_totalWLe->text().toDouble();
    } else {
        mainWidth = m_totalWLe->text().toDouble();
        mainHeight = m_totalHLe->text().toDouble();
    }

    qDebug() << "开始创建主体结构......";
    //添加主体
    cutomitem data;
    data.name = "主体箱";
    data.color = QColor(128, 128, 128);
    data.type = Main;
    data.rect = QRectF(0,0,mainWidth,mainHeight);
    emit addMainRect(data,0.0,0.0,0.0,0.0);

    qInfo() << "主体结构创建完成......";
    qDebug() << "开始创建电芯模组......";
    createBlockItem();
}

void T_Rules::createBlockItem()
{    
    m_list_groups.clear();
    //首先根据模组数量以及模组排布方式进行结构超限验证
    if(!judgeGroup())
    {
        qCritical() << "创建电芯模组失败，请更换电芯或者重新选择参数尝试......";
        return;
    }

    double blockWidth;
    double blockHeight;
    switch (m_layout) {
    case LW:
    {
        blockWidth = m_blockInfo.length;
        blockHeight = m_blockInfo.width;
    }
    break;
    case LH:
    {
        blockWidth = m_blockInfo.length;
        blockHeight = m_blockInfo.height;
    }
    break;
    case HW:
    {
        blockWidth = m_blockInfo.height;
        blockHeight = m_blockInfo.width;
    }
    break;
    case WL:
    {
        blockWidth = m_blockInfo.width;
        blockHeight = m_blockInfo.length;
    }
    break;
    case WH:
    {
        blockWidth = m_blockInfo.width;
        blockHeight = m_blockInfo.height;
    }
    break;
    case HL:
    {
        blockWidth = m_blockInfo.height;
        blockHeight = m_blockInfo.length;
    }
    break;
    default:
        break;
    }

    int singleNum = m_blockSingleNumLe->text().toInt();
    int sumNum = m_blockNumLe->text().toInt();
    int groupNum = sumNum/singleNum;
    //添加电芯串
    cutomitem data;
    data.name = "电芯串";
    data.color = QColor(54, 126, 127);
    data.type = Block;
    data.rect = QRectF(0,0,blockWidth,blockHeight);
    double space = BLOCKINTERVAL; //写死
    int num = m_blockSingleNumLe->text().toInt();

    for(int i = 0; i < groupNum; i++) {
        //创建block包
        emit addBlockRect(data,space,num,m_direction);
        QString tmp_name = QString("%1_%2").arg(data.name).arg(i+1);
        m_list_groups.append(tmp_name);
    }

    //根据排列方式设置放置位置和间隔
    if(m_list_groups.count() < 2 && m_list_groups.count() > 0) {
        qInfo() << "电芯创建完成......";
        //计算结果
        qDebug() << "开始分析结果数据......";
        calcResult();

        return;
    }

    QString firstItemName = m_list_groups.value(0); // 首行首元素
    QString prevRowFirst = firstItemName; // 上一行首元素
    QString currentRowFirst = firstItemName; // 当前行首元素
    for(int i = 1; i < m_list_groups.count(); i++){
        QStringList tmpList;
        // 每次只取相邻的两个元素：前一个(i-1)和当前(i)
        tmpList.append(m_list_groups.value(i-1));
        tmpList.append(m_list_groups.value(i));

        if(m_layout_group == HX) {
            emit cchildItemSpaceSignal(tmpList,MODELGROUPINTERVAL_H,0.0,"右侧对齐","顶部对齐");
        }
        else if(m_layout_group == HX) {
            emit cchildItemSpaceSignal(tmpList,0.0,MODELGROUPINTERVAL_H,"左侧对齐","底部对齐");
        }
        else if(m_layout_group == DHDL) {
            //根据模组数量以及，最大支持行列数进行判断，一行一行的排,即先把列数排满
            // 判断是否换行（当前索引是新行的开始）
            bool isNewRowStart = ((i) % m_col_max == 0);
            if(isNewRowStart) {
                // 1. 处理换行对齐：当前行首与上一行首垂直对齐
                QStringList verticalList;
                verticalList.append(prevRowFirst); // 上一行首元素
                verticalList.append(m_list_groups.value(i)); // 当前行首元素

                emit cchildItemSpaceSignal(verticalList, 0.0, MODELGROUPINTERVAL_V,"左侧对齐","底部对齐");

                // 2. 更新行首记录
                currentRowFirst = m_list_groups.value(i); // 设置新行首
                prevRowFirst = currentRowFirst; // 当前行变为上一行

                // 3. 处理新行内的第一个元素（不需要水平排列）
                continue; // 跳过后续水平排列处理
            }
            else {
                // 行内元素水平排列
                emit cchildItemSpaceSignal(tmpList,MODELGROUPINTERVAL_H,0.0,"右侧对齐","顶部对齐");
            }
        }
    }

    qInfo() << "电芯创建完成......";
    //计算结果
    qDebug() << "开始分析结果数据......";
    calcResult();
}

void T_Rules::calcModelGroupCount()
{    
    //首先判断串数是否为偶数，不是的话则加1
    int cCount = m_cLe->text().toInt();
    if(cCount % 2 != 0) {
        cCount += 1;
        m_cLe->setText(QString::number(cCount));
    }
    //计算最小模组数量
    qDebug() << "开始计算模组最小数量......";
    while(1) {
        if(m_splitInt > cCount) {
            qCritical() << "未找到合适点单模组电芯数，请调整电压或者容量";
            return;
        }
        else if(cCount % m_splitInt != 0) {
            m_splitInt += 1;
        } else {
            int ret = cCount / m_splitInt;
            int tmpret = ret % m_bLe->text().toInt();
            if(ret > m_pack_count_max || (tmpret != 0)) {
                m_splitInt += 1;
            } else {
                qInfo() << "单模组电芯数量为：" << ret << " 模组最小数量为：" << m_splitInt;
                m_blockSingleNumLe->setText(QString::number(ret));
                m_groupNumLe->setText(QString::number(m_splitInt));
                break;
            }
        }
    }

    qDebug() << "开始矫正单模组电芯数量以及模组最小数量......";
    //计算单模组是否超结构尺寸
    double blockSumWidth = 0.0;   //总长
    double blockSumHeight = 0.0;  //总宽
    int block_single_sum = m_blockSingleNumLe->text().toInt();

    //计算单模组总长度与总宽度
    calcCommon(blockSumWidth,blockSumHeight,block_single_sum);
    //比对结果
    qDebug() << "开始对比结构尺寸是否超限......";
    int ret = judgeSplit(blockSumWidth,blockSumHeight);
    if(!ret) {
        qWarning() << "重新计算验证......";
        //重新计算验证
        m_splitInt += 1;
        calcModelGroupCount();
    } else {
        //赋值单个模块的大小
        m_single_w = blockSumWidth;
        m_single_h = blockSumHeight;
    }
}

void T_Rules::calcCommon(double &blockSumWidth, double &blockSumHeight, int sum)
{
    double length = m_blockInfo.length;
    double width = m_blockInfo.width;
    double height = m_blockInfo.height;
    if(m_direction == 0){
        //水平放置
        switch (m_layout) {
        case LW:
        {
            blockSumWidth = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = width;
            m_sum_block_dh = height;
        }
        break;
        case LH:
        {
            blockSumWidth = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = height;
            m_sum_block_dh = width;
        }
        break;
        case HW:
        {
            blockSumWidth = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = width;
            m_sum_block_dh = length;
        }
        break;
        case WL:
        {
            blockSumWidth = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = length;
            m_sum_block_dh = height;
        }
        break;
        case WH:
        {
            blockSumWidth = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = height;
            m_sum_block_dh = length;
        }
        break;
        case HL:
        {
            blockSumWidth = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = length;
            m_sum_block_dh = width;
        }
        break;
        default:
            break;
        }
    }else if(m_direction == 1) {
        //垂直放置
        switch (m_layout) {
        case LW:
        {
            blockSumWidth = length;
            blockSumHeight = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = height;
        }
        break;
        case LH:
        {
            blockSumWidth = length;
            blockSumHeight = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = width;
        }
        break;
        case HW:
        {
            blockSumWidth = height;
            blockSumHeight = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = length;
        }
        break;
        case WL:
        {
            blockSumWidth = width;
            blockSumHeight = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = height;
        }
        break;
        case WH:
        {
            blockSumWidth = width;
            blockSumHeight = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = length;
        }
        break;
        case HL:
        {
            blockSumWidth = height;
            blockSumHeight = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = width;
        }
        break;
        default:
            break;
        }
    } else if(m_direction == 2) {
        //堆叠放置
        switch (m_layout) {
        case LW:
        {
            blockSumWidth = length;
            blockSumHeight = width;
            m_sum_block_dh = (sum * height) + ((sum - 1) * BLOCKINTERVAL);
        }
        break;
        case WL:
        {
            blockSumWidth = width;
            blockSumHeight = length;
            m_sum_block_dh = (sum * height) + ((sum - 1) * BLOCKINTERVAL);
        }
        break;
        default:
            break;
        }
    }
}

bool T_Rules::judgeSplit(double blockSumWidth,double blockSumHeight)
{
    double mainWidth = m_totalWLe->text().toDouble();
    double mainHeight = m_totalHLe->text().toDouble();
    double mainHD = m_totalHDLe->text().toDouble();

    if(blockSumWidth < mainWidth && blockSumHeight < mainHeight && m_sum_block_dh < mainHD) {
        int nowBlockNum = m_blockSingleNumLe->text().toInt();
        int nowGroupNum = m_cLe->text().toInt() / nowBlockNum;
        qInfo() << "矫正完成，单模组电芯数量为：" << nowBlockNum << " 模组最小数量为：" << nowGroupNum;
        return true;
    } else {
        qWarning() << "宽度、高度、或者厚度已经超出范围，需要分割多个......正在重新计算模组数量......";
        return false;
    }
}

bool T_Rules::judgeGroup()
{
    double mainWidth = m_totalWLe->text().toDouble();
    double mainHeight = m_totalHLe->text().toDouble();
    // int groupNum = m_groupNumLe->text().toInt();
    int singleNum = m_blockSingleNumLe->text().toInt();
    int sumNum = m_blockNumLe->text().toInt();
    int groupNum = sumNum/singleNum;
    double tmpSumWidth = 0.0;
    double tmpSumHeight = 0.0;
    int row_col_max = 0;
    if(m_layout_group == HX) {
        tmpSumWidth = (groupNum * m_single_w) + ((groupNum - 1) * MODELGROUPINTERVAL_H);
        tmpSumHeight = m_single_h;
    } else if(m_layout_group == ZX) {
        tmpSumWidth = m_single_w;
        tmpSumHeight = (groupNum * m_single_h) + ((groupNum - 1) * MODELGROUPINTERVAL_V);
    } else if(m_layout_group == DHDL) {
        //计算横向最多摆多少个
        int hx_row_max = 0;
        int hx_col_max = 0;
        while(1) {
            double tmpWidth = (hx_col_max * m_single_w) + ((hx_col_max - 1) * MODELGROUPINTERVAL_H);
            if(tmpWidth >= mainWidth) {
                qInfo() << "最大能放列数：" << hx_col_max - 1;
                m_col_max = hx_col_max - 1;
                break;
            }
            hx_col_max += 1;
        }
        //计算横向最多摆多少列
        while(1) {
            double tmpHeight = (hx_row_max * m_single_h) + ((hx_row_max - 1) * MODELGROUPINTERVAL_V);
            if(tmpHeight >= mainHeight) {
                qInfo() << "最大能放行数：" << hx_row_max - 1;
                m_row_max = hx_row_max - 1;
                break;
            }
            hx_row_max += 1;
        }

        row_col_max = (hx_row_max - 1) * (hx_col_max - 1);
    }

    //判断是否结构超限
    if(tmpSumWidth < mainWidth && tmpSumHeight < mainHeight && m_layout_group != DHDL) {
        return true;
    } else if(groupNum <= row_col_max && m_layout_group == DHDL) {
        return true;
    } else {
        qCritical() << "模组排列超限，此配置方案行不通。。。。。。";
        return false;
    }
}

void T_Rules::calcResult()
{
    // int group_num = m_groupNumLe->text().toInt();
    int singleNum = m_blockSingleNumLe->text().toInt();
    int sumNum = m_blockNumLe->text().toInt();
    int group_num = sumNum/singleNum;
    qInfo() << "模组的数量结果为：" << QString::number(group_num) << " 个";

    int block_num = m_blockSingleNumLe->text().toInt();
    qInfo() << "单个模组电芯数量：" << QString::number(block_num) << " 个";

    //计算总电压
    double sumVol = group_num * block_num *m_blockInfo.voltage;
    qInfo() << "总电压输出结果为：" << QString::number(sumVol,'f',2) << " V";

    //计算总容量
    double sumAh = sumVol * m_blockInfo.kWh;
    qInfo() << "总容量输出结果为：" << QString::number(sumAh,'f',2) << " Ah";
}
